#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

void OnMouseAction(int event, int x, int y, int flags, void *ustc);

Point clickCor;
Point curCor;
bool isClicked = 0;
bool isDrew = 0;
Mat srcImg;
Mat dstImg;
Mat toolImg;

int main(int, char **)
{
    VideoCapture cap("/home/llrt/视频/lake.avi");
    VideoWriter writer("lake.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 30.0, cv::Size(960, 544));
    namedWindow("srcImg");
    setMouseCallback("srcImg", OnMouseAction, &srcImg);

    while (true)
    {
        isDrew = 0;
        cap >> srcImg;
        inRange(srcImg, Scalar(95, 120, 140), Scalar(120, 150, 180), dstImg);
        imshow("srcImg", srcImg);
        imshow("dstImg", dstImg);
        waitKey(0);
        if (isDrew)
        {
            writer.operator<<(toolImg);
        }
        else
        {
            writer.operator<<(srcImg);
        }
        
    }

    return 0;
}

void OnMouseAction(int event, int x, int y, int flags, void *ustc)
{
    if (event == EVENT_LBUTTONDOWN)
    {
        clickCor = Point(x, y);
        isClicked = true;
        return;
    }
    if (event == EVENT_MOUSEMOVE && isClicked == true)
    {
        srcImg.copyTo(toolImg);
        curCor = Point(x, y);
        rectangle(toolImg, Rect(clickCor, curCor), Scalar(0, 0, 255));
        imshow("srcImg", toolImg);
    }
    if (event == EVENT_LBUTTONUP)
    {
        isClicked = false;
        isDrew = 1;
        srcImg.copyTo(toolImg);
        curCor = Point(x, y);
        rectangle(toolImg, Rect(clickCor, curCor), Scalar(0, 0, 255));
        imshow("srcImg", toolImg);
    }
}